 #!/usr/bin/env python
 # coding: utf-8
 
"""
Copyright (C) 2010  Fabio A Martins

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
"""

import os, sys
import optparse
import re
sys.path.append('..')
from os import environ
environ['DJANGO_SETTINGS_MODULE'] = 'django_freedb.settings'

from django_freedb.freedb.models import *

def main():
    p = optparse.OptionParser()
    p.add_option('--dir', '-d', default=".", help='root dir with freedb files')
    options, arguments = p.parse_args()
    added = []
    alread_exist = []
    encode_error = []
    count = 0
    for root, dirs, files in os.walk(options.dir):
        for name in files:
            outmsg = '%s/%s' % (root,name)
            #fh = open('../freedb-update-20100201-20100301/reggae/d30ed60f','r')
            fh = open('%s/%s' % (root,name),"r")
            tracks = []
            DISCID = None
            for line in fh.readlines():
                if not re.match('^#', line): # exclude commented lines
                    """ get disc id """
                    if re.match('^DISCID=', line):
                        DISCID = line[line.find('=')+1:].strip()

                    """ get disc title and artist """
                    if re.match('^DTITLE=', line):
                        DTITLE_AND_DARTIST = line[line.find('=')+1:]
                        DTITLE = DTITLE_AND_DARTIST[DTITLE_AND_DARTIST.find('/')+2:].strip()
                        DARTIST = DTITLE_AND_DARTIST[:DTITLE_AND_DARTIST.find('/')-1].strip()
                        outmsg += ' %s ' % DTITLE_AND_DARTIST
                    """ get year """
                    if re.match('^DYEAR=', line):
                        DYEAR = line[line.find('=')+1:]
                        
                    """ get genre """
                    if re.match('^DGENRE=', line):
                        DGENRE = line[line.find('=')+1:].strip()
                        
                    """ append song list """
                    
                    if re.match('^TTITLE(\d+)=', line):
                        track_name = line[line.find('=')+1:].strip()
                        track_number = int(re.sub('TTITLE','',line[:line.find('=')].strip()))+1
                        track = {'track_number':track_number, 'track_name': track_name}
                        tracks.append(track)

            if Disc.objects.filter(freedbid=DISCID):
                alread_exist.append(DISCID)
                outmsg += '[ignored]'
            else:
                try:
                    """ get or create genre """
                    genre, created = Genre.objects.get_or_create(title=DGENRE)
                    """ get or create artist """
                    artist, created = Artist.objects.get_or_create(name=DARTIST)
                    
                    # create disc
                    disc = Disc()
                    disc.freedbid = DISCID
                    disc.artist = artist
                    disc.genre = genre
                    disc.title = DTITLE
                    disc.year = DYEAR
                    disc.save()
                    
                    """ add album tracks """
                    for i in tracks:
                        t = Track()
                        t.track_number = i.get('track_number')
                        t.title = i.get('track_name')
                        t.disc_id = disc.id
                        t.save()

                    added.append(DISCID)
                    outmsg += '[added]'
                except:
                    encode_error.append(DISCID)
                    outmsg += '[encoding error]'

            print outmsg
            count += 1
    
    print 'total files %s' % count
    print 'added %s' % len(added)
    print 'error (encode error) %s' % len(encode_error)
    print 'already registered (not inserted) %s' % len(alread_exist)

if __name__ == '__main__':
    main()
